const req = require("express/lib/request");
const Tutorial = require("../models/tutorial.model");
exports.findAll = (req,res) =>{
    let title = req.query.title;
    Tutorial.getAll(title,(err,data) =>{
        if(err){
            res.status(500).json({
                message:err.message || "Some error occurred while retrieving tutorials."
            })
        }else{
            res.json(data);
        }
    })
};

exports.findById = (req,res) =>{
    let id = req.params.id;
    Tutorial.getById(id,(err,data) =>{
        if(err){
            if(err.kind == "not_found"){
                res.status(404).json({
                    message:`Not found Tutorial with id ${id}`
                })
            }else{
                res.status(500).json({
                    message:`Error retrieving Tutorial with id ${id}`
                })
            }
        }else{
            res.json(data);
        }
    })
};

exports.findAllPublished = (req,res) =>{
    Tutorial.getAllPublished((err,data) =>{
        if(err){
            res.status(500).json({
                message:"error"
            })
        }else{
            res.json(data);
        }
        
    })
};

exports.save = (req,res) =>{
    if(!req.body){
        res.status(400).json({
            message:"Content can not be empty"
        })
    }
    const tutorial = new Tutorial({
        title:req.body.title,
        description:req.body.description,
        published:req.body.published
    });

    Tutorial.save(tutorial,(err,data) =>{
        if(err){
            res.status(500).json({
                message:"created tutorial error" + err
            })
        }else{
            res.json(data);
        }
    })
};

exports.updateById = (req,res) =>{
    if(!req.body){
        res.status(400).json({
            message:"request body is empty"
        })
    }
    console.log(req.body);
    let id = req.params.id;
    let tutorial = new Tutorial({
        title:req.body.title,
        description:req.body.description,
        published:req.body.published
    });
    Tutorial.updateById(id,tutorial,(err,data) =>{
        if(err){
            if(err.kind == "not_found"){
                res.status(404).json({
                    message:`Not found Tutorial by id ${id}`
                })
            }else{
                res.status(500).json({
                    message:`error:${err}`
                })
            }
        }else{
            res.json(data);
        }
    })
};

exports.removeById = (req,res) =>{
    let id = req.params.id;
    Tutorial.removeById(id,(err,data) =>{
        if(err){
            res.status(500).json({
                message:`error:${err}`
            })
        }else{
            res.json(data);
        }
    })
}